using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace Solver
{
	/// <summary>
	/// Find the maximum sum travelling from the top of the triangle to the base.
	/// </summary>
	public class Problem018 : SelfChecker, IProblem
	{
		private static readonly string[] Lines = @"
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
".Replace(Environment.NewLine, "/").Split('/');

		public int Id
		{
			get { return 18; }
		}

		public string Solve()
		{
			return Solve(Lines).ToString();
		}

		public static int Solve(IEnumerable<string> lines)
		{
			var triangle = lines.Where(l => l.Length > 0)
				.Select(l => l.Split(' ').Select(n => Int32.Parse(n)).ToArray()).ToArray();
			for (var row = 1; row < triangle.Length; row++)
			{
				triangle[row][0] += triangle[row - 1][0];
				for (var idx = 1; idx < triangle[row].Length - 1; idx++)
					triangle[row][idx] += Math.Max(triangle[row - 1][idx - 1], triangle[row - 1][idx]);
				triangle[row][triangle[row].Length - 1] += triangle[row - 1][triangle[row - 1].Length - 1];
			}
			return triangle[triangle.Length - 1].Max();
		}

		[Test]
		public override void Check()
		{
			Assert.AreEqual(23, Solve(new[] { "3", "7 5", "2 4 6", "8 5 9 3" }));
			Assert.AreEqual(1074, Solve(Lines));
		}
	}
}